package com.mall.b2c.service.impl;

import com.mall.b2c.dao.IntergralDao;
import com.mall.b2c.dao.IntergralShopProductDao;
import com.mall.b2c.domain.intergral.IntergralDomain;
import com.mall.b2c.domain.intergral.IntergralLogDomain;
import com.mall.b2c.domain.intergral.ShopProductDomain;
import com.mall.b2c.domain.member.MemberDomain;
import com.mall.b2c.domain.order.CartItemDomain;
import com.mall.b2c.domain.order.OrderDomain;
import com.mall.b2c.domain.order.OrderItemDomain;
import com.mall.b2c.enums.IntergralLogType;
import com.mall.b2c.service.IntergralLogService;
import com.mall.b2c.service.IntergralService;
import com.mall.b2c.service.IntergralShopProductService;
import com.mall.b2c.service.MemberService;
import com.mall.common.exception.NoticeException;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.impl.BaseServiceImpl;
import org.hsqldb.lib.HashSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by chen on 16/12/15.
 */
@Service
@Transactional
public class IntergralServiceImpl extends  BaseServiceImpl<IntergralDomain, Long> implements IntergralService {

    @Resource
    public IntergralLogService logService;

    @Resource
    public MemberService memberService;

    @Resource
    public void setBaseDao(IntergralDao intergralDao) {
        super.setBaseDao(intergralDao);
    }

    public void saveIntergralDomain(MemberDomain memberDomain){

        IntergralDomain domain = new IntergralDomain();
        domain.setNum(0);
        domain.setMember(memberDomain);
        domain.setSite_id(0);
        persist(domain);

    }


    public   IntergralDomain getByMemberId(Long memberId){
        MemberDomain member = memberService.find(memberId);
        if (member == null) {
            throw new NoticeException("会员不存在");
        }
        Finder finder = Finder.create("from IntergralDomain bean where bean.member.id = :memberId");
        finder.setParam("memberId", memberId);
        Object obj = finder.findUniqueByHQL();
        if(obj == null){
            IntergralDomain domain = new IntergralDomain();
            domain.setNum(0);
            domain.setMember(member);
            domain.setSite_id(0);
            persist(domain);
            return domain;
        }
        return (IntergralDomain) obj;
    }

    /***
     * 积分日志
     *
     * @param memberId
     * @param price
     * @param logType
     * @param remark
     */
    @Transactional(propagation= Propagation.REQUIRED)
    public void alterations(Long memberId, int price, IntergralLogType logType, String remark) {
        IntergralDomain intergral = getByMemberId(memberId);
        MemberDomain member = intergral.getMember();
        IntergralLogDomain logdomain = new IntergralLogDomain();
        if (logType.equals(IntergralLogType.addnum)) {
            intergral.setNum(intergral.getNum() + price);
            logdomain.setSurplus(intergral.getNum());
            member.setPoint(member.getPoint() + price);
            memberService.update(member);
        } else {
            if (intergral.getNum() < price) {
               throw  new NoticeException("您的积分余额不足");
            } else {
                intergral.setNum(intergral.getNum() - price);
                logdomain.setSurplus(intergral.getNum());
           }
        }
        logdomain.setMember(intergral.getMember());
        logdomain.setNums(price);
        logdomain.setLogText(remark);
        logdomain.setLogtype(logType);
        logService.persist(logdomain);
        update(intergral);
    }


    @Transactional(propagation = Propagation.REQUIRED)
    public void grantGoodsIntergral(Long memberId, OrderDomain order) {
        Set<OrderItemDomain> items = order.getOrderItems();
        int score = 0;
        for (Iterator it = items.iterator(); it.hasNext(); ) {
            Object o = it.next();
            OrderItemDomain itemDomain = (OrderItemDomain) o;
            int intergral = itemDomain.getSalePrice()
                    .multiply(BigDecimal.valueOf(itemDomain.getQuantity())
                            .multiply(BigDecimal.valueOf(itemDomain.getGoods().getIntegralRate())))
                    .intValue() / 100;
            if (intergral > 0) {
                alterations(memberId, intergral, IntergralLogType.addnum, "购买商品" + itemDomain.getProductName() + ",数量:" + itemDomain.getQuantity());
                score += intergral;
            }
        }

        //被邀请人消费，邀请人二级奖励
        MemberDomain member = memberService.find(memberId);
        if(member != null){
            //邀请人
            MemberDomain inverter = member.getInviter();
            if(inverter != null){
                alterations(inverter.getId(), new BigDecimal(score*0.1).setScale(0, BigDecimal.ROUND_HALF_UP).intValue(), IntergralLogType.addnum, "徒弟（一级）消费奖励");
                //邀请人的邀请人
                MemberDomain inverter2 = inverter.getInviter();
                if(inverter2 != null){
                    alterations(inverter2.getId(), new BigDecimal(score*0.01).setScale(0, BigDecimal.ROUND_HALF_UP).intValue(), IntergralLogType.addnum, "徒弟（二级）消费奖励");
                }
            }
        }
    }
}







